<template>
  <nav class="fixed top-0 w-full bg-white shadow-sm z-50">
    <div class="w-1200 mx-auto h-16 flex items-center justify-between">
      <div class="flex items-center space-x-8">
        <h1 class="text-2xl font-bold text-#dc5655">
          <img
            :src="$store.state.logoImg"
            class="logo-img h-14"
            alt=""
            @click="$router.push('/')"
          />
        </h1>

        <div class="relative">
          <input type="text" placeholder="搜索目的地、主题、路线、地名" v-model="searchData"
            class="w-96 h-10 pl-5 pr-4 rounded-full border-1 border-#dc5655 bg-gray-100 focus:outline-none focus:ring-2 focus:ring-#ed5b5a text-sm"
            @keyup.enter="handleSearch()" 
            @input="handleInput()"
          />
          <i class="fas fa-search absolute right-4 text-#dc5655 text-sm cursor-pointer h-10 leading-10" style="line-height: 2.5rem;" @click="handleSearch()"></i>
        </div>
      </div>

      <!--未登录 -->
      <div class="flex items-center space-x-6" v-show="!userInfo.username">
        <button 
          class="rounded-full whitespace-nowrap bg-#dc5655 text-white px-6 py-2 hover:bg-#ed5b5a text-sm"
          @click="
            $router.push({
              path: '/login',
              query: {
                rePath: $route.path,
                query: JSON.stringify($route.query)
              }
            })"
        >
          <span>请登录</span>
        </button>
      </div>

      <!--已登录 -->
      <div class="flex items-center space-x-6 text-sm hidden group-hover:block mr-1" v-show="!!userInfo.username">
        <div class="flex items-center space-x-4">
          <button class="!rounded-button whitespace-nowrap text-gray-600 hover:text-#dc5655" 
            @click="goUserCenter('/home/TourOrder')" v-show="!!userInfo.username"
          >
            <i class="far fa-clipboard mr-2"></i>我的订单
          </button>
          <button class="!rounded-button whitespace-nowrap text-gray-600 hover:text-#dc5655" 
            @click="goUserCenter('/home/MsgList')" v-show="!!userInfo.username"
          >
            <i class="far fa-bell mr-2"></i>
            <span class="relative">
              我的消息
              <span class="absolute -top-1 -right-2 w-2 h-2 bg-red-500 rounded-full hidden"></span>
            </span>
          </button>
          <div class="username-p group flex items-center space-x-2 cursor-pointer">
            <div class="relative">
              <Avatar class="w-8 h-8 rounded-full object-cover bg-gray-600" 
                :src="baseURL + '/' + userInfo.face" 
                icon="person" 
                size="small"
              />
            </div>
            <span class="text-gray-800 font-medium">{{ userInfo.name ? userInfo.name : userInfo.username | secrecyMobile }}</span>
            <transition name='fade'>
              <ul class="drop-items">
                <li @click="goUserCenter('/home')">我的主页</li>
                <li @click="goUserCenter('/home/Coupons')">优惠券</li>
                <li @click="goUserCenter('/home/Favorites')">我的收藏</li>
                <li @click="signOutFun">退出登录</li>
              </ul>
            </transition>
          </div>
        </div>
      </div>
    </div>
  </nav>
</template>

<script>
import storage from '@/plugins/storage.js';
import { staticUrl } from '@/plugins/request';
import { cartGoodsAll } from '@/api/cart.js';
import { logout } from '@/api/account.js';


export default {
  name: 'M-Header',
  created() {
    if (storage.getItem('userInfo')) {
      this.userInfo = JSON.parse(storage.getItem('userInfo'));
    }
  },

  data() {
    return {
      config: require('@/config'),
      baseURL: staticUrl,
      userInfo: {},      // 用户信息 
      shoppingCart: [],  // 购物车
      searchData: "",    // 搜索内容
      previousValue: '', // 上一次搜索内容
      hasValueChanged: false, // 搜索内容是否改变
    };
  },
  computed: {
    // 购物车商品数量
    cartNum() {
      return this.$store.state.cartNum;
    }, 
  },
  methods: {
    goToPay() { // 跳转购物车
      let url = this.$router.resolve({
        path: '/cart'
      });
      window.open(url.href, '_blank');
    },
    myInfo() { // 跳转会员中心
      let url = this.$router.resolve({
        path: '/home'
      });
      window.open(url.href, '_blank');
    },
    signOutFun() { // 退出登录
      logout().then(res => {
        storage.removeItem('accessToken');
        storage.removeItem('refreshToken');
        storage.removeItem('userInfo');
        storage.removeItem('cartNum');
        this.$store.commit('SET_CARTNUM', 0)
        this.$router.push('/login');
      });
    },
    goUserCenter(path) {
      // 跳转我的订单，我的足迹、收藏等
      if (this.userInfo.username) {
        this.$router.push({path: path});
      } else {
        this.$Modal.confirm({
          title: '请登录',
          content: '<p>请登录后执行此操作</p>',
          okText: '立即登录',
          cancelText: '继续浏览',
          onOk: () => {
            this.$router.push({
              path: '/login',
              query: {
                rePath: this.$router.history.current.path,
                query: JSON.stringify(this.$router.history.current.query)
              }
            });
          }
        });
      }
    },
    shopEntry() {
      // 店铺入驻
      if (storage.getItem('accessToken')) {
        let routeUrl = this.$router.resolve({
          path: '/shopEntry',
          query: {id: 1}
        });
        window.open(routeUrl.href, '_blank');
      } else {
        this.$router.push('login');
      }
    },
    getCartList() {
      // 获取购物车列表
      if (this.userInfo.username) {
        cartGoodsAll().then((res) => {
          this.shoppingCart = res.result.skuList;
          this.$store.commit('SET_CARTNUM', this.shoppingCart.length);
          this.Cookies.setItem('cartNum', this.shoppingCart.length);
        });
      }
    },

    //input 回车事件，希望是值有变化时，才执行
    handleInput() {
      // 去除首尾空格后比较
      const trimmedCurrent = this.searchData.trim();
      const trimmedPrevious = this.previousValue.trim();
      if (trimmedCurrent !== trimmedPrevious) {
          this.hasValueChanged = true;
      }
      this.previousValue = this.searchData;
    },

    handleSearch() {
      if (!this.hasValueChanged) {
        return false
      }
      // 全平台搜索商品
      const url = this.$route.path;
      if (url == "/goodsList") {
        this.$emit("search", this.searchData);
      } else {
        const pushData = {
          path: "/goodsList",
          query: { title: this.searchData },
        };
        // 店铺内搜索
        // if (this.storeId && this.onlyStore) {
        //   pushData.query.storeId = this.storeId;
        // }
        this.$router.push(pushData);
      }
    },
  }
};
</script>

<style scoped lang="scss">

.box {
  width: 100%;
  font-size: 14px !important;
  height: 34px;
  line-height: 34px;
  background: #444;
  color: #fff;
  font-weight: 600;
}

.nav {
  display: flex;
  flex-direction: row;
  justify-content: space-between;

}

.nav ul {
  list-style: none;
}

.nav li {
  cursor: pointer;
  float: left;
  height: 34px;
  line-height: 34px;
  margin-right: 0px;
}

.nav a,
.nav-item {
  font-size: 13px;
  font-weight: 600;
  text-decoration: none;
  cursor: pointer;
  color: #fff;
  height: 34px;
  line-height: 34px;
  border: 1px red solid;
  display: inline-block;
  text-align: justify;
}

.nav-item {
  padding-left: 20px;
}

.location a {
  border-left: none;
}


.icon {
  color: gray;
  vertical-align: middle;
}

.city {
  padding: 10px 15px;
}

.city-item {
  font-weight: bold;
  cursor: pointer;
  padding: 5px;
}

.city-item:hover {
  color: $theme_color;
}

.person-icon {
  color: $theme_color;
  background-color: #f0cdb2;
}


.shopping-cart-img {
  margin-right: 15px;
  width: 40px;
  height: 40px;
}

.shopping-cart-img img {
  width: 100%;
}

.shopping-cart-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-content: space-between;
  width: 200px;
  overflow: hidden;
  font-size: 12px;
  line-height: 20px;
}


.shopping-cart-null {
  padding: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.cart-null-icon {
  font-size: 38px;
  margin-bottom: 15px;
}

.shopping-cart-null span {
  font-size: 12px;
  line-height: 16px;
}

.username-p {
  position: relative;

  div {
    cursor: pointer;
    height: 36px;
    line-height: 36px;
    span {
      margin-left: 5px;
    }
    span.person-icon{
      margin-top: -3px;
    }
    span.username {
      line-height: 36px;
      height: 36px;
    }
  }

  .drop-items {
    position: absolute;
    display: none;
    top: 45px;
    left: 0;
    right: 0;
    margin: 0 auto;
    padding: 5px 10px;
    z-index: 20;
    height: 150px;
    background-color: #fff;
    border: 1px solid #eee;
    box-shadow: 2px 2px 7px #999;
    width: 150px;

    li {
      color: rgb(107, 106, 106);
      width: 100%;
      border-bottom: 1px solid rgb(207, 206, 206);
      font-weight: normal;
      text-align: left;
      height: 35px;
      line-height: 35px;
      &:last-child {
        border: none;
      }

      &:hover {
        cursor: pointer;
        color: $theme_color;
      }
    }

    &::before {
      position: absolute;
      top: -20px;
      left: 30px;
      content: '';
      width: 0;
      height: 0;
      border: 10px solid #999;
      border-color: transparent transparent #fff transparent;
    }

    &::after {
      content: '';
      position: absolute;
      width: 80px;
      height: 20px;
      top: -20px;
      left: 0;
    }
  }

  &:hover {
    .drop-items {
      display: block;
    }
  }
}

.my-page {
  padding: 3px 5px;
  width: 180px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.my-page a {
  margin: 0px;
  padding: 0px;
  border: none;
}

.my-info {
  padding: 5px;
  width: 50%;
  height: 100%;
  text-align: center;
  cursor: pointer;
}

.my-info:hover {
  box-shadow: 0px 0px 5px #ccc;
}

.my-info i {
  font-size: 28px;
}

.my-info p {
  font-size: 12px;
}

.sign-out {
  padding: 5px;
  width: 50%;
  height: 100%;
  text-align: center;
  cursor: pointer;
}

.sign-out:hover {
  box-shadow: 0px 0px 5px $border_color;
}

.sign-out i {
  font-size: 28px;
}

.sign-out p {
  font-size: 12px;
}

.goods-title:hover {
  color: $theme_color;
}

.cart-badge {
  position: absolute;
  right: -8px;
  font-style: normal;
  background-color: $theme_color;
  color: #fff;
  font-size: 12px;
  width: 17px;
  height: 17px;
  border-radius: 10px;
  line-height: 17px;
  text-align: center;
  z-index: 3;
  top: 3px;
}

.shopping-cart-box {
  padding: 8px 0;
  cursor: pointer;
  display: flex;
  align-items: center;
  border-bottom: 1px #ccc dotted;
}

.shopping-cart-list {
  padding: 10px 10px;
  box-sizing: border-box;
  max-height: 300px;
  overflow-y: scroll;
  color: #333;

}

.shopping-cart-detail {
  color: #999;
  font-size: 12px;

}

.shopping-price {
  color: $theme_color;
  font-size: 14px;
  font-weight: bold;
}

</style>
